package com.zhz.lib.project.controller;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.zhz.lib.project.ibatis.domain.news.News;
import com.zhz.lib.project.service.custom.CustomService;
import com.zhz.lib.project.service.news.NewsService;
import com.zhz.lib.project.vo.custom.CustomVO;
import com.zhz.lib.project.vo.news.NewsVO;
import com.zhz.project.common.util.alibaba.StringUtil;
import com.zhz.project.common.util.ibatispage.IbatisPage;
import com.zhz.project.common.util.zhzutil.ZhzHttpRequestUtil;
import com.zhz.project.common.util.zhzutil.ZhzStringUtil;

/**
 * @author LiWei <a href="mailto:liwei2672@gmail.com">liwei2672@gmail.com</a>
 * @version 创建时间：2010-5-3 下午03:22:27
 * 
 */
@Controller
@RequestMapping("/news.htm")
public class NewsController {
    private static Logger logger      = Logger.getLogger(NewsController.class);
    private static int    firstResult = 0;
    private static int    maxResults  = 7;
    @Autowired
    private NewsService   newsService;

    @Autowired
    private CustomService customService;

    @Autowired
    private IbatisPage    ibatisPage;

    private static String pageSql     = "selectAllNewsByPage";
    private static String countSql    = "selectAllNewsCount";

    /**
     * 最新消息列表(Ibatis)
     * 
     * @param model
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(method = RequestMethod.GET)
    public String getIbatisList(ModelMap model, HttpServletRequest request,
                                HttpServletResponse response) {
        // 获取顶级模块
        List<CustomVO> customVOList = customService.getTopCustom();
        model.put("customVOList", customVOList);

        try {
            // 传递给Ibatis的map
            Map map = new HashMap();

            // 当前页
            String indexPage = ZhzStringUtil.ISOtoUTF8AfterTrimIfNotNull(request
                .getParameter("indexPage"));
            map.put("indexPage", indexPage);

            // 搜索框的值
            String keyword = ZhzStringUtil.ISOtoUTF8AfterTrimIfNotNull(request
                .getParameter("keyword"));
            String keywordOut = null;
            if (StringUtil.isNotBlank(keyword)) {
                keyword = URLDecoder.decode(keyword);
                keywordOut = URLEncoder.encode(URLEncoder.encode(keyword));
            }
            map.put("title", keyword);

            ZhzHttpRequestUtil
                .writeMapToModelMap(model, ibatisPage.getPage(map, countSql, pageSql));

            // 将News转换为NewsVO
            List<News> newsList = (List<News>) model.get("list");
            List<NewsVO> newsVOList = new ArrayList<NewsVO>();
            if (newsList != null && newsList.size() > 0) {
                for (News news : newsList) {
                    NewsVO newsVO = new NewsVO();
                    try {
                        BeanUtils.copyProperties(newsVO, news);
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("从news复制到newsVO时发生异常", e);
                    }
                    newsVOList.add(newsVO);
                }
            }

            model.put("list", newsVOList);

            // 获取置顶最新消息
            List<NewsVO> topNewsVOList = newsService.getTopNews(firstResult, maxResults);
            model.put("topNewsVOList", topNewsVOList);

            model.put("keyword", keyword);

            return "news";
        } catch (Exception e) {
            logger.error(e.toString());
            return null;
        }

    }

    /**
     * 
     * 根据id获取最新消息
     * 
     * @param model
     * @param request
     * @param response
     * @param id
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(method = RequestMethod.GET, params = "event=single")
    public String getSingleNews(ModelMap model, HttpServletRequest request,
                                HttpServletResponse response, @RequestParam("id") int id) {
        // 获取顶级模块
        List<CustomVO> customVOList = customService.getTopCustom();
        model.put("customVOList", customVOList);

        model.put("news", newsService.getNewsById(id));
        newsService.newsHitPlusOne(id);
        return "newsDetail";
    }

}
